package my.soft.aiteacher.utils;

import org.springframework.data.redis.core.RedisTemplate;

import java.util.concurrent.TimeUnit;


public class SimpleRedisLock implements ILock {
    private final String LOCK_PREFIX = "lock:";

    private RedisTemplate<String, String> redisTemplate;
    private String name;

    public SimpleRedisLock(RedisTemplate<String, String> redisTemplate, String name) {
        this.redisTemplate = redisTemplate;
        this.name = name;
    }

    @Override
    public Boolean lock(Long time) {
        String thread = String.valueOf(Thread.currentThread().getId());
        Boolean success = redisTemplate.opsForValue().setIfAbsent(LOCK_PREFIX + name, thread, time, TimeUnit.SECONDS);
        return Boolean.TRUE.equals(success);
    }

    @Override
    public Boolean unlock() {
        Boolean delete = redisTemplate.delete(LOCK_PREFIX + name);
        return delete;
    }
    @Override
    public Boolean isLocked() {
        return Boolean.TRUE.equals(redisTemplate.hasKey(LOCK_PREFIX + name));
    }
}
